<template>
  <div class="system-crmTalent-dialog-container">
    <el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="85%">
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="基础信息" name="base">
          <el-form ref="crmTalentDialogFormRef" :model="state.ruleForm" :rules="state.rules" size="default" label-width="120px">
            <el-row :gutter="35">

              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                <el-form-item label="人才类型" prop="talentType">
                  <el-select v-model="state.ruleForm.talentType" placeholder="请选择人才类型" clearable class="w100">
                    <el-option
                    v-for="dict in talent_type"
                    :key="Number(dict.value)"
                    :label="dict.label"
                    :value="Number(dict.value)"
                     />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                <el-form-item label="业务类型" prop="busiType">
                  <el-select v-model="state.ruleForm.busiType" placeholder="请选择业务类型" clearable class="w100">
                    <el-option
                    v-for="dict in busi_type"
                    :key="Number(dict.value)"
                    :label="dict.label"
                    :value="Number(dict.value)"
                     />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                <el-form-item label="业务办理进度" prop="progressType">
                  <el-select v-model="state.ruleForm.progressType" placeholder="请选择业务办理进度" clearable class="w100">
                    <el-option
                    v-for="dict in progress_type"
                    :key="Number(dict.value)"
                    :label="dict.label"
                    :value="Number(dict.value)"
                     />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                <el-form-item label="申请日期" prop="applyDate">
                  <el-date-picker clearable
                                  v-model="state.ruleForm.applyDate"
                                  type="date"
                                  value-format="YYYY-MM-DD"
                                  placeholder="选择申请日期">
                  </el-date-picker>
                </el-form-item>
              </el-col>

              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                <el-form-item label="姓名" prop="talentName">
                  <el-input v-model="state.ruleForm.talentName" placeholder="请输入姓名" clearable></el-input>
                </el-form-item>
              </el-col>

              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                <el-form-item label="性别" prop="talentGender">
                <el-select v-model="state.ruleForm.talentGender" placeholder="请选择性别" clearable class="w100">
                    <el-option
                    v-for="dict in sys_user_sex"
                    :key="Number(dict.value)"
                    :label="dict.label"
                    :value="Number(dict.value)"
                     />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                <el-form-item label="手机号码" prop="talentPhone">
                  <el-input v-model="state.ruleForm.talentPhone" placeholder="请输入手机号码" clearable></el-input>
                </el-form-item>
              </el-col>

              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                <el-form-item label="民族" prop="talentNationality">
                 <el-select v-model="state.ruleForm.talentNationality" placeholder="请选择民族" clearable class="w100">
                    <el-option
                    v-for="dict in talent_nationality"
                    :key="Number(dict.value)"
                    :label="dict.label"
                    :value="Number(dict.value)"
                     />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                <el-form-item label="政治面貌" prop="talentPolitical">
                <el-select v-model="state.ruleForm.talentPolitical" placeholder="请选择政治面貌" clearable class="w100">
                    <el-option
                    v-for="dict in talent_political"
                    :key="Number(dict.value)"
                    :label="dict.label"
                    :value="Number(dict.value)"
                     />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                <el-form-item label="婚姻状况" prop="talentMarrige">
                <el-select v-model="state.ruleForm.talentMarrige" placeholder="请选择婚姻状况" clearable class="w100">
                    <el-option
                    v-for="dict in talent_marrige"
                    :key="Number(dict.value)"
                    :label="dict.label"
                    :value="Number(dict.value)"
                     />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                <el-form-item label="证件号码" prop="talentIdenno">
                  <el-input v-model="state.ruleForm.talentIdenno" placeholder="请输入证件号码" clearable></el-input>
                </el-form-item>
              </el-col>

              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                <el-form-item label="户籍所在地" prop="talentRegistration">
                  <el-input v-model="state.ruleForm.talentRegistration" placeholder="请输入户籍所在地" clearable></el-input>
                </el-form-item>
              </el-col>

              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                <el-form-item label="现居住地" prop="talentResidential">
                  <el-input v-model="state.ruleForm.talentResidential" placeholder="请输入现居住地" clearable></el-input>
                </el-form-item>
              </el-col>

              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                <el-form-item label="国内最高学历" prop="domesticHighestDegree">
                <el-select v-model="state.ruleForm.domesticHighestDegree" placeholder="请选择国内最高学历" clearable class="w100">
                    <el-option
                    v-for="dict in domestic_highest_degree"
                    :key="Number(dict.value)"
                    :label="dict.label"
                    :value="Number(dict.value)"
                     />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                <el-form-item label="审核状态" prop="domesticAuditStatus">
                  <el-select v-model="state.ruleForm.domesticAuditStatus" placeholder="请选择审核状态" clearable class="w100">
                    <el-option
                    v-for="dict in domestic_audit_status"
                    :key="Number(dict.value)"
                    :label="dict.label"
                    :value="Number(dict.value)"
                     />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                <el-form-item label="国内最高学位" prop="domesticHighestDiploma">
                <el-select v-model="state.ruleForm.domesticHighestDiploma" placeholder="国内最高学位" clearable class="w100">
                    <el-option
                    v-for="dict in domestic_highest_diploma"
                    :key="Number(dict.value)"
                    :label="dict.label"
                    :value="Number(dict.value)"
                     />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                <el-form-item label="照片路径" prop="photoPath">
        <el-upload
          action="/fileApi/manage/file/uploadFile"
          :headers="headers"
          :show-file-list="false"
          :on-success="(res) => handleSuccess(res)"
          :before-upload="beforeUpload"
          accept="image/*"
        >
          <!-- 图片预览区域 -->
          <div v-if="state.ruleForm.photoPath">
            <el-image 
              :src="state.ruleForm.photoPath" 
              fit="cover"
              style="width: 60px; height: 60px; border-radius: 6px;"
              :preview-src-list="[state.ruleForm.photoPath]"
            />
            <div class="el-upload__tip">点击重新上传</div>
          </div>
          
          <!-- 上传按钮 -->
          <el-button v-else size="small" type="primary">上传照片</el-button>
        </el-upload>
                </el-form-item>
              </el-col>
             <!--
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                <el-form-item label="登录密码" prop="loginPass">
                  <el-input v-model="state.ruleForm.loginPass" placeholder="请输入登录密码" clearable></el-input>
                </el-form-item>
              </el-col> -->
            </el-row>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="教育信息" name="teach"><Teach ref="TeachNode" /></el-tab-pane>
        <el-tab-pane label="学习经历" name="study"><Study ref="StudyNode" /></el-tab-pane>
        <el-tab-pane label="工作经历" name="work"><Work ref="WorkNode" /></el-tab-pane>
        <el-tab-pane label="子女信息" name="child"><Children ref="ChildrenNode" /></el-tab-pane>
        <el-tab-pane label="留学信息" name="studyAbroad"><StudyAbroad ref="StudyAbroadNode" /></el-tab-pane>
        <el-tab-pane label="电子附件" name="attachments"><Attachments ref="AttachmentsNode" /></el-tab-pane>
      </el-tabs>
          
        
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancel" size="default">取 消</el-button>
          <el-button type="primary" @click="onSubmit" size="default">{{ state.dialog.submitTxt }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="dictDialog">
  import { defineAsyncComponent, nextTick, reactive, ref, getCurrentInstance, defineProps, defineEmits } from 'vue';
  import { useCrmTalentApi } from '/@/api/system/talent';
  import { ElMessage } from "element-plus";
  
  import type { TabsPaneContext } from 'element-plus'

  import Teach from './components/Teach.vue';
  import Study from './components/Study.vue';
  import Work from './components/Work.vue';
  import Children from './components/Child.vue';
  import StudyAbroad from './components/StudyAbroad.vue';
  import Attachments from './components/Attachments.vue';
  import { Session } from '/@/utils/storage';

  const TeachNode = ref<any>(null)
  const StudyNode = ref<any>(null)
  const WorkNode = ref<any>(null)
  const ChildrenNode = ref<any>(null)
  const StudyAbroadNode = ref<any>(null)
  const AttachmentsNode = ref<any>(null)

  const activeName = ref('base')
  const headers = ref({Authorization: ''})
  
  // 定义子组件向父组件传值/事件
  const emit = defineEmits(['refresh']);

  const { proxy } = getCurrentInstance();
  const { sys_user_sex,talent_type,busi_type,progress_type,talent_nationality,talent_political,talent_marrige,domestic_highest_degree,domestic_audit_status,domestic_highest_diploma,apply_entity,audit_action,school_step,import_type } = proxy.parseDict("talent_type","sys_user_sex",
         "busi_type","progress_type","talent_nationality","talent_political","talent_marrige","domestic_highest_degree","domestic_audit_status","domestic_highest_diploma","apply_entity","audit_action","school_step","import_type");
  // 定义变量内容
  const useCrmTalent = useCrmTalentApi();
  const crmTalentDialogFormRef = ref();
  const state = reactive({
    ruleForm: {
      talentType: '',
      busiType: '',
      progressType: '',
      applyDate: '',
      talentName: '',
      talentGender: '',
      talentPhone: '',
      talentNationality: '',
      talentPolitical: '',
      talentMarrige: '',
      talentIdenno: '',
      talentRegistration: '',
      talentResidential: '',
      domesticHighestDegree: '',
      domesticAuditStatus: '',
      domesticHighestDiploma: '',
      photoPath: '',
      loginPass: '',
    },
    dialog: {
      isShowDialog: false,
      type: '',
      title: '',
      submitTxt: '',
    },
    rules: {
      talentType: { required: true, message: '请输入人才类型', trigger: 'blur' },
      talentName: { required: true, message: '请输入姓名', trigger: 'blur' },
      talentGender: { required: true, message: '请输入人才性别', trigger: 'blur' },
      talentPhone: { required: true, message: '请输入手机号码', trigger: 'blur' },
      talentIdenno: { required: true, message: '请输入证件号码', trigger: 'blur' },
    },
  });

  // 点击tabs
  const handleClick = (tab: TabsPaneContext, event: Event) => {
    console.log(tab, event)
  }
  // 打开弹窗
  const openDialog = (type: string, row) => {
    const token = `${Session.get('token')}`
    headers.value.Authorization = token;
    AttachmentsNode.value && AttachmentsNode.value.setHeader()
    resetForm();
    if (type === 'edit') {
      useCrmTalent.getCrmTalentDetailById(row.id).then(res => {
        state.ruleForm = res as any;
        TeachNode.value && TeachNode.value!.setData(res.auditRecords ?? [])
        StudyNode.value && StudyNode.value!.setData(res.learnExperiences ?? [])
        WorkNode.value && WorkNode.value!.setData(res.workExperiences ?? [])
        ChildrenNode.value && ChildrenNode.value!.setData(res.childrenInformations ?? [])
        StudyAbroadNode.value && StudyAbroadNode.value!.setData(res.studyAbroadInformations ?? [])
        state.dialog.title = '修改人才';
        state.dialog.submitTxt = '修 改';
      });
    } else {
      state.dialog.title = '新增人才';
      state.dialog.submitTxt = '新 增';
    }
    state.dialog.type = type;
    state.dialog.isShowDialog = true;
  };
  // 关闭弹窗
  const closeDialog = () => {
    state.dialog.isShowDialog = false;
  };
  // 取消
  const onCancel = () => {
    closeDialog();
  };

  // 提交
  const onSubmit = () => {
  let prama = {
      ...state.ruleForm,
      auditRecords: TeachNode.value!.getData(),
      learnExperiences: StudyNode.value!.getData(),
      workExperiences: WorkNode.value!.getData(),
      childrenInformations: ChildrenNode.value!.getData(),
      studyAbroadInformations: StudyAbroadNode.value!.getData(),
      digitalAttachFiles: AttachmentsNode.value!.getData()
    }
    console.log(JSON.stringify(StudyNode.value!.getData()));
    
    // 验证表单
    Promise.all([
      currentValidate(crmTalentDialogFormRef),
    ]).then(res => {
      const validateResult = res.every(item => !!item);
      if (validateResult) {
        if(state.dialog.type == 'add'){
          useCrmTalent.createCrmTalent(prama).then(() => {
            ElMessage.success('创建成功');
            closeDialog();
            emit('refresh');
          });
        } else {
          useCrmTalent.updateCrmTalent(prama).then(() => {
            ElMessage.success('修改成功');
            closeDialog();
            emit('refresh');
          });
        }
      } else {
        ElMessage.error("表单校验未通过，请重新检查提交内容");
      }
    });
  };

  // 主表-表单组件验证
  const currentValidate = (pageRef) => {
    return new Promise((resolve) => {
      pageRef.value.validate((valid: boolean) => {
        if (valid) resolve(valid);
      });
    });
  };



  
  const resetForm = () => {
    state.ruleForm = {
      talentType: '',
      busiType: '',
      progressType: '',
      applyDate: '',
      talentName: '',
      talentGender: '',
      talentPhone: '',
      talentNationality: '',
      talentPolitical: '',
      talentMarrige: '',
      talentIdenno: '',
      talentRegistration: '',
      talentResidential: '',
      domesticHighestDegree: '',
      domesticAuditStatus: '',
      domesticHighestDiploma: '',
      photoPath: '',
      loginPass: '',
    }
  }
  // 暴露变量
  defineExpose({
    openDialog,
  });

  const beforeUpload = (file) => {
  const isImage = /\.(jpg|jpeg|png|gif|webp)$/i.test(file.name)
  const isLt2M = file.size / 1024 / 1024 < 2
  
  if (!isImage) {
    ElMessage.error('只能上传图片格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 上传成功处理
const handleSuccess = (response) => {
  if (response.code === "0000") {
    // 根据实际API返回结构调整路径
    state.ruleForm.photoPath = response.data
    ElMessage.success('上传成功!')
  } else {
    ElMessage.error(`上传失败: ${response.message}`)
  }
}
</script>

